#define _CRT_SECURE_NO_WARNINGS 1
#include"SLlist.h"

SLNode* CreateNode(ElementType x)
{
	SLNode* NewNode = (SLNode*)malloc(sizeof(SLNode));
	if (NewNode == NULL)
	{
		printf("malloc fail\n");
		exit(-1);
	}
	NewNode->data = x;
	NewNode->next = NULL;
	return NewNode;
}

void SLlistPushBack(SLNode** pphead, ElementType x)
{
	assert(pphead);

	if (*pphead == NULL)
	{
		*pphead = CreateNode(x);
	}
	else
	{
		SLNode* p = *pphead;
		while (p->next != NULL)
		{
			p = p->next;
		}
		p->next = CreateNode(x);
	}
}

void SLlistPushFront(SLNode** pphead, ElementType x)
{
	assert(pphead);
	SLNode* front = CreateNode(x);
	front->next = *pphead;
	*pphead = front;
}

void SLlistPopBack(SLNode** pphead)
{
	assert(pphead);
	assert(*pphead);
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLNode* p = *pphead;
		SLNode* p2 = NULL;
		while (p->next)
		{
			p2 = p;
			p = p->next;
		}
		free(p);
		p2->next = NULL;
	}
}

void SLlistPopFront(SLNode** pphead)
{
	assert(pphead);
	assert(*pphead);
	SLNode* p = *pphead;
	*pphead = (*pphead)->next;
	free(p);
}

void SLlistPrint(SLNode* phead)
{
	SLNode* p = phead;
	while (p != NULL)
	{
		printf("%d->", p->data);
		p = p->next;
	}
	printf("NULL\n");
}

int SLlistSize(SLNode* phead)
{
	int Size = 0;
	SLNode* p = phead;
	while (p)
	{
		Size++;
		p = p->next;
	}
	return Size;
}

SLNode* SLlistFind(SLNode* phead, ElementType x)
{
	assert(phead);
	SLNode* p = phead;
	while (p)
	{
		if (p->data == x)
			return p;
		else
			p = p->next;
	}
	return NULL;
}

bool SLlistEmpty(SLNode* phead)
{
	return phead == NULL ? true : false;
}

void SLlistInsert(SLNode** pphead, SLNode* pos, ElementType x)
{
	assert(pphead);
	assert(pos);
	if (pos == *pphead)
	{
		SLlistPushFront(pphead, x);
	}
	else
	{
		SLNode* p = *pphead;
		while (p->next != pos)
		{
			p = p->next;
		}
		SLNode* NewNode = CreateNode(x);
		NewNode->next = pos;
		p->next = NewNode;
	}
}

void SLlistInsertAfter(SLNode* pos, ElementType x)
{
	assert(pos);
	SLNode* p = CreateNode(x);
	p->next = pos->next;
	pos->next = p;
}

void SLlistErase(SLNode** pphead, SLNode* pos)
{
	assert(pphead);
	assert(pos);
	if (pos == *pphead)
	{
		SLlistPopFront(pphead);
	}
	else
	{
		SLNode* p = *pphead;
		while (p->next != pos)
		{
			p = p->next;
		}
		p->next = pos->next;
		free(pos);
		pos = NULL;
	}
}

void SLlistEraseAfter(SLNode* pos)
{
	assert(pos);
	assert(pos->next);

	SLNode* next = pos->next;
	pos->next = next->next;
	free(next);
	next = NULL;
}

void SLlistDestory(SLNode** pphead)
{
	assert(pphead);
	SLNode* p = *pphead;
	while (p)
	{
		SLNode* next = p->next;
		free(p);
		p = next;
	}
	*pphead = NULL;
}